package su.msk.jet.team01.chatik.server.data;

import java.util.Formatter;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;


public class Room {
	private final List<Client> clients = new LinkedList<Client>();
	private String name;

	public String getName() {
		return name;
	}

	public Room(String name) {
		this.name = name;
	}

	public List<Client> getClients() {
		return clients;
	}
	
	public void addClient(Client client) {
		synchronized (clients) {
			clients.add(client);
		}
	}

	public void removeClient(Client client) {
		synchronized (clients) {
			clients.remove(client);
			if (this != DataManager.getDefaultRoom() && clients.isEmpty()) {
				DataManager.removeRoom(name);
			}
		}
	}

	public void send(String msg, Object... args) {
		Formatter formatter = new Formatter();
		formatter.format(Locale.getDefault(), msg, args);
		String result = formatter.out().toString();
		formatter.close();
		
		synchronized (clients) {
			for (Client client : clients) {
				client.send(result);
			}
		}
	}
}
